<template>
  <el-dialog
    v-model="visible"
    :title="form.id ? '编辑敏感词' : '添加敏感词'"
    width="30%"
    @closed="handleClose"
  >
    <el-form :model="form" label-width="80px">
      <el-form-item label="敏感词">
        <el-input v-model="form.keyword" placeholder="请输入敏感词" />
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="form.status">
          <el-radio :label="0">正常</el-radio>
          <el-radio :label="1">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from "vue";
import { ElMessage } from "element-plus";
import { createSensitiveWord, updateSensitiveWord } from "@/api/sensitiveWord";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  editData: {
    type: Object,
    default: () => null,
  },
});

const emit = defineEmits(["update:modelValue", "success"]);

const visible = ref(false);
const form = ref({
  id: "",
  keyword: "",
  status: 0,
});

// 监听visible变化
watch(
  () => props.modelValue,
  (val) => {
    visible.value = val;
  }
);

// 监听visible变化，同步父组件
watch(
  () => visible.value,
  (val) => {
    emit("update:modelValue", val);
  }
);

// 监听编辑数据
watch(
  () => props.editData,
  (val) => {
    if (val) {
      form.value = {
        id: val.id,
        keyword: val.keyword,
        status: val.status,
      };
    }
  },
  { immediate: true }
);

// 处理关闭
const handleClose = () => {
  form.value = {
    id: "",
    keyword: "",
    status: 0,
  };
};

// 提交表单
const handleSubmit = async () => {
  if (!form.value.keyword.trim()) {
    ElMessage.warning("请输入敏感词");
    return;
  }

  try {
    if (form.value.id) {
      // 编辑模式
      await updateSensitiveWord(form.value.id, {
        word: form.value.keyword.trim(),
        status: form.value.status,
      });
      ElMessage.success("编辑成功");
    } else {
      // 添加模式
      await createSensitiveWord({
        word: form.value.keyword.trim(),
        status: form.value.status,
      });
      ElMessage.success("添加成功");
    }
    visible.value = false;
    emit("success");
  } catch (error) {
    ElMessage.error(form.value.id ? "编辑失败" : "添加失败");
  }
};
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 